const request = require('request');
const fs = require('fs');
const iconv = require('iconv-lite');
const cheerio = require('cheerio');
const controllersWatermark = that = {
	/**
	 * 初始化
	 * @param {Object} req
	 * @param {Object} res
	 */
	async init(req, res) {
		const query = req.query;
		const { url } = query;
		const getUrl = that.getStrUrl(url);
		// const dd = 'https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200fg10000cb5pumjc77u2ierlbd70&ratio=720p&line=0';
		request({
			url: encodeURI('https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200fg10000cb5pumjc77u2ierlbd70&ratio=720p&line=0'),
			headers: {
				// 'Connection': 'keep-alive',
				// 'content-type': 'application/json',
				// 'Accept': '*/*',
				// 'Sec-Fetch-Site': 'cross-site',
				// 'Sec-Fetch-Mode': 'cors',
				// 'Sec-Fetch-Dest': 'empty',
				// 'Accept-Language': 'zh-CN,zh;q=0.8',
				'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
			},
			encoding: null,
			timeout: 5000
		}, (error, res, body) => {
			var html = iconv.decode(body, 'gb2312');
			//配置cheerio
			var $ = cheerio.load(html, {
				decodeEntities: false
			});
			//ans为cheerio筛选出来的内容，这里选择的是包含.container选择器的标签
			var ans = $('video').html();
			console.log(cheerio.load(html).html())
		})
		console.log('getUrlgetUrl', getUrl)
		// if (!getUrl) res.send({
		// 	code: -1,
		// 	msg: '未检测到解析地址',
		// 	data: null
		// });
		// if (that.checkUrl(getUrl, 'douyin')) {
		// 	that.douyin(getUrl, res);
		// };
	},
	/**
	 * 抖音去水印
	 * @param {Object} url 解析地址
	 * @param {Object} res 响应对象
	 */
	async douyin(url, res) {
		const _id = await that.getID(url, /video\/(.*)\?/);
		const _url = `https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${_id}`;
		const _body = await that.getReqBody(_url);
		const _deUrl = _body.item_list[0]['video']["play_addr"]["url_list"][0].replace('playwm', 'play');
		const _resultUrl = await that.req_get(_deUrl);
		res.send({
			code: 0,
			// d: _resultUrl
		})
		console.log('_body_body===>', _deUrl);
	},
	req_get(url, headers = {}) {
		const _headers = JSON.stringify(headers) != '{}' ? headers : {
			'Connection': 'keep-alive',
			'content-type': 'application/json',
			'Accept': '*/*',
			'Sec-Fetch-Site': 'cross-site',
			'Sec-Fetch-Mode': 'cors',
			'Sec-Fetch-Dest': 'empty',
			'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
		};
		return new Promise((resolve) => {
			request({
				url: encodeURI(url),
				headers: {
					'Connection': 'keep-alive',
					'content-type': 'application/json',
					'Accept': '*/*',
					'Sec-Fetch-Site': 'cross-site',
					'Sec-Fetch-Mode': 'cors',
					'Sec-Fetch-Dest': 'empty',
					'Accept-Language': 'zh-CN,zh;q=0.8',
					'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
				},
				encoding: null,
				timeout: 5000,
				// strictSSL: false,
				// rejectUnauthorized: true,
			}, (error, res, body) => {
				if (!error && res.statusCode == 200) {
					//指定body当中的编码类型
					var html = iconv.decode(body, 'gb2312');
					//配置cheerio
					var $ = cheerio.load(html, {
						decodeEntities: false
					});
					//ans为cheerio筛选出来的内容，这里选择的是包含.container选择器的标签
					var ans = $('.container').html();
					resolve(html);
					// console.log(html);
					// console.log(body)
				} else resolve(null);
			})
		})
	},
	/**
	 * 获取请求的内容
	 * @param {Object} url 请求地址
	 */
	getReqBody(url) {
		return new Promise((resolve) => {
			request(encodeURI(url), (error, res) => {
				if (!error && res.statusCode == 200) {
					const _data = typeof JSON.parse(res.body) != 'undefined' ? JSON.parse(res.body) : {};
					resolve(_data);
				} else resolve(null);
			})
		})
	},
	/**
	 * 根据链接地址和正则规则获取相应id
	 * @param {Object} url 链接地址
	 * @param {Object} reg 正则表达式
	 */
	getID(url, reg) {
		return new Promise((resolve) => {
			request(encodeURI(url), (error, res) => {
				try {
					if (!error && res.statusCode == 200) resolve(res.request.href.match(reg)[1]);
					else resolve(null);
				} catch (e) {
					resolve(null);
				}
			})
		})
	},
	/**
	 * 获取字符串中的url地址
	 * @param {String} s 字符串
	 */
	getStrUrl(s) {
		var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
		var reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
		s = s.match(reg);
		return (s && s.length ? s[0] : null);
	},
	/**
	 * 检查链接中是否有该值
	 * @param {Object} url 链接地址
	 * @param {Object} val 检查的值
	 */
	checkUrl(url, val) {
		return url.indexOf(val) > -1;
	}
};
module.exports = controllersWatermark;
